package com.mrdeer.web.service.sys.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mrdeer.common.entity.beans.PageEntity;
import com.mrdeer.common.entity.dto.SettingDTO;
import com.mrdeer.common.entity.sys.Setting;
import com.mrdeer.common.exception.BusinessException;
import com.mrdeer.web.mapper.SettingMapper;
import com.mrdeer.web.service.sys.SysSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
@Transactional
public class SysSettingServiceImpl extends ServiceImpl<SettingMapper, Setting> implements SysSettingService {

    @Resource
    private SettingMapper settingMapper;

    @Override
    public Setting get(String id) {
        return settingMapper.selectById(id);
    }

    @Override
    public Setting add(Setting setting) {
        if (settingMapper.insert(setting) > 0) {
            return settingMapper.selectById(setting.getId());
        }
        throw new BusinessException("add failed");
    }

    @Override
    public boolean delete(String id) {
        Setting setting = getById(id);
        if (null == setting) {
            throw new BusinessException("The setting does not exist");
        }
        return settingMapper.deleteById(id) > 0;
    }

    @Override
    public Setting update(Setting setting) {
        if (settingMapper.updateById(setting) > 0) {
            Setting select = settingMapper.selectById(setting.getId());
            return select;
        }
        throw new BusinessException("The setting update failed");
    }

    @Override
    public Setting getById(String id) {
        return settingMapper.selectById(id);
    }

    @Override
    public Page<Setting> list(SettingDTO dto) {
        if (null == dto.getPage()) {
            dto.setPage(new PageEntity());
        }
        return settingMapper.selectPage(dto.getPage().convert(), fuzzyQuery(dto));
    }

    @Override
    public LambdaQueryWrapper<Setting> fuzzyQuery(SettingDTO dto) {
        LambdaQueryWrapper<Setting> queryWrapper = Wrappers.<Setting>query().lambda();
        if (null != dto) {
            if (StrUtil.isNotBlank(dto.getValue())) {
                queryWrapper.like(Setting::getValue, dto.getValue());
            }
            if (StrUtil.isNotBlank(dto.getId())) {
                queryWrapper.like(Setting::getId, dto.getId());
            }
        }
        return queryWrapper;
    }
}
